package com.yj.auto.plugin.lucene.model;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;

import com.jfinal.log.Log;
import com.yj.auto.plugin.lucene.utils.LuceneUtil;

public class AutoIndexSearcher {
	private static final Log logger = Log.getLog(AutoIndexSearcher.class);
	IndexSearcher searcher = null;

	public AutoIndexSearcher() throws Exception {
		Directory dir = LuceneUtil.getDirectory();
		IndexReader reader = DirectoryReader.open(dir);
		searcher = new IndexSearcher(reader);
	}

	protected void close() throws Exception {
		searcher.getIndexReader().close();
	}

	public boolean release() {
		boolean success = true;
		try {
			close();
		} catch (Exception e) {
			logger.error("close index reader error", e);
			success = false;
		}
		return success;
	}

	public Document doc(int docID) throws IOException {
		return searcher.doc(docID);
	}

	/**
	 * 分页查询
	 *
	 * @param page
	 *            当前页数
	 * @param pageSize
	 *            每页显示条数
	 * @param searcher
	 *            searcher查询器
	 * @param query
	 *            查询条件
	 */
	public TopDocs search(int page, int pageSize, Query query) throws IOException {
		TopDocs docs = null;
		if (query == null) {
			logger.error(" Query is null  ");
			return null;
		}
		ScoreDoc before = null;
		if (page != 1) {
			TopDocs docsBefore = searcher.search(query, (page - 1) * pageSize);
			ScoreDoc[] scoreDocs = docsBefore.scoreDocs;
			if (scoreDocs.length > 0) {
				before = scoreDocs[scoreDocs.length - 1];
			}
		}
		docs = searcher.searchAfter(before, query, pageSize);
		return docs;
	}
}
